package com.example.XueCuApp.Utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IDCardReader {
    protected int CODE = 0;
    protected String TAG = "IDCardReader";
    private Context mContext = null;
    protected boolean isOpen;
    protected String sKey = "";

    //���ڲ�����ض���
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;


    protected String PATH = "/dev/ttySAC3";

    protected int BAUDRATE = 115200;    //a320


    public IDCardReader(Context theContext) {
        isOpen = false;
        mContext = theContext;
    }

    public boolean PowerOnReader() {
        Log.d(TAG,"IDcardReader PowerOnReader");
        return true;
    }

    public boolean PowerOffReader() {
        return false;
    }

    public String getReaderPowerStatus() {
        return "";
    }

    public String ReadSAMID(String[] sRet) {
        return "";
    }

    public boolean InitReader(byte[] byLicBuf) {
        return false;
    }

    public void ReleaseReader() {
    }

    public IDCardInfo ReadBaseCardInfo(String[] sRet) {
        return null;
    }

    public IDCardInfo ReadAllCardInfo(String[] sRet) {
        return null;
    }

    //-----------------------------------------------------------------------------------------------
    protected String parseNation(int code) {
        switch (code) {
            case 01:
                return ("汉");
            case 02:
                return ("蒙古");
            case 03:
                return ("回");
            case 04:
                return ("藏");
            case 05:
                return ("维吾尔");
            case 06:
                return ("苗");
            case 07:
                return ("彝");
            case 8:
                return ("壮");
            case 9:
                return ("布依");
            case 10:
                return ("朝鲜");
            case 11:
                return ("满");
            case 12:
                return ("侗");
            case 13:
                return ("瑶");
            case 14:
                return ("白");
            case 15:
                return ("土家");
            case 16:
                return ("哈尼");
            case 17:
                return ("哈萨克");
            case 18:
                return ("傣");
            case 19:
                return ("黎");
            case 20:
                return ("傈僳");
            case 21:
                return ("佤");
            case 22:
                return ("畲");
            case 23:
                return ("高山");
            case 24:
                return ("拉祜");
            case 25:
                return ("水");
            case 26:
                return ("东乡");
            case 27:
                return ("纳西");
            case 28:
                return ("景颇");
            case 29:
                return ("柯尔克孜");
            case 30:
                return ("土");
            case 31:
                return ("达斡尔");
            case 32:
                return ("仫佬");
            case 33:
                return ("羌");
            case 34:
                return ("布朗");
            case 35:
                return ("撒拉");
            case 36:
                return ("毛南");
            case 37:
                return ("仡佬");
            case 38:
                return ("锡伯");
            case 39:
                return ("阿昌");
            case 40:
                return ("普米");
            case 41:
                return ("塔吉克");
            case 42:
                return ("怒");
            case 43:
                return ("乌孜别克");
            case 44:
                return ("俄罗斯");
            case 45:
                return ("鄂温克");
            case 46:
                return ("德昂");
            case 47:
                return ("保安");
            case 48:
                return ("裕固");
            case 49:
                return ("京");
            case 50:
                return ("塔塔尔");
            case 51:
                return ("独龙");
            case 52:
                return ("鄂伦春");
            case 53:
                return ("赫哲");
            case 54:
                return ("门巴");
            case 55:
                return ("珞巴");
            case 56:
                return ("基诺");
            case 97:
                return ("其他");
            case 98:
                return ("外国血统中国籍人士");
            default:
                return ("");
        }
    }

    protected Bitmap parsePhoto(byte[] wltData) {

        byte[] byLicData = {(byte) 0x05, (byte) 0x00,
                (byte) 0x01, (byte) 0x00, (byte) 0x5B, (byte) 0x03, (byte) 0x33,
                (byte) 0x01, (byte) 0x5A, (byte) 0xB3, (byte) 0x1E, (byte) 0x00};
        Init();
        unpack(wltData, byLicData);
        //WltToBmpBuffer(wltData, bmpData, sKey);

        return null;//BitmapFactory.decodeByteArray(bmpData, 0, bmpData.length);
    }


    public static int Init() {
        //return wltInit("/wltlib");
        return com.ivsign.android.IDCReader.IDCReaderSDK
                .wltInit(Environment.getExternalStorageDirectory() + "/wltlib");
    }

    public static int unpack(byte[] wltdata, byte[] licdata) {
        return com.ivsign.android.IDCReader.IDCReaderSDK.wltGetBMP(wltdata, licdata);
    }


    //------------------------------------------------------------------------------------------------------------
    // SerialPort
    //------------------------------------------------------------------------------------------------------------
    protected void closeSerialPort() {
        try {
            mFileInputStream.close();
            mFileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        com.ivsign.android.IDCReader.prop.close();
    }


    protected boolean openSerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
/*  		
		// Check access permission 
		if (!device.canRead() || !device.canWrite()) {
			try {
				//* Missing read/write permission, trying to chmod the file
				Process su;
				su = Runtime.getRuntime().exec("/system/bin/su");
				String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
						+ "exit\n";
				su.getOutputStream().write(cmd.getBytes());
				if ((su.waitFor() != 0) || !device.canRead()
						|| !device.canWrite()) {
					throw new SecurityException();
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new SecurityException();
			}
		}
*/

        mFd = com.ivsign.android.IDCReader.prop.open(device.getAbsolutePath(), baudrate, flags);
        if (mFd == null) {
            Log.e(TAG, "native open returns null");
            throw new IOException();
        }


        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
        return true;
    }

    // Getters and setters
    private InputStream getInputStream() {
        return mFileInputStream;
    }

    private OutputStream getOutputStream() {
        return mFileOutputStream;
    }

    protected int read(byte recvBuf[], int recvLen, long waitTime) throws IOException {
        long lBeginTime = System.currentTimeMillis();//���µ�ǰ�����
        long lCurrentTime = 0;
        int nRet = 0;
        int nReadedSize = 0;


        while (true) {

            if (mFileInputStream.available() > 0) {
                nRet = mFileInputStream.read(recvBuf, nReadedSize, (recvLen - nReadedSize));
                if (nRet > 0) {
                    nReadedSize += nRet;
                    if (recvLen == nReadedSize) return 0;
                }
            }

            try {
                Thread.sleep(10);
                lCurrentTime = System.currentTimeMillis();
                if ((lCurrentTime - lBeginTime) > waitTime) {
                    return 2;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    protected int read(byte recvBuf[], long waitTime) throws IOException {
        long lBeginTime = System.currentTimeMillis();//���µ�ǰ�����
        long lCurrentTime = 0;
        int nRet = 0;
        int nReadedSize = 0;


        while (true) {

            if (mFileInputStream.available() > 0) {
                nRet = mFileInputStream.read(recvBuf, nReadedSize, 1);
                if (nRet > 0) {
                    nReadedSize += nRet;
                }
            }

            try {
                Thread.sleep(10);
                lCurrentTime = System.currentTimeMillis();
                if ((lCurrentTime - lBeginTime) > waitTime) {
                    return nReadedSize;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    protected void write(byte[] data) throws IOException {
        while (mFileInputStream.available() > 0) mFileInputStream.read();
        mFileOutputStream.write(data);
    }

    //-----------------------------------------------------------------------------------------------
    private void displayError(String sMsg) {
        AlertDialog.Builder localBuilder = new AlertDialog.Builder(mContext);
        localBuilder.setTitle("Error");
        localBuilder.setMessage(sMsg);
        localBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
            }
        });
        localBuilder.show();
    }
}
